package com.talkyun.openx.server.core;

import com.talkyun.openx.server.session.Session;
import com.talkyun.openx.server.session.SessionManager;

public class ServiceContext extends AbstractContext {
    public static final String REQ_IP = "_req_ip";
    public static final String REQ_HOST = "_req_host";
    private static final ThreadLocal<ServiceContext> CTX_LOCAL = new ThreadLocal<ServiceContext>();
    private static final SessionManager SESSION_MANAGER = SessionManager.get();

    private ServiceRequest serviceRequest;

    private ServiceContext(String sessionId) {
        super(sessionId);
    }

    @Deprecated
    public static ServiceContext getContext() {
        return get();
    }

    public static ServiceContext get() {
        ServiceContext ctx = CTX_LOCAL.get();
        if (ctx != null) {
            return ctx;
        }
        throw new RuntimeException("Context not exists!");
    }

    public static ServiceContext getContext(String sessionId) {
        if (sessionId == null) {
            throw new RuntimeException("SessionId is null!");
        }
        ServiceContext ctx = new ServiceContext(sessionId);
        CTX_LOCAL.set(ctx);
        return ctx;
    }

    public Session getSession() {
        return SESSION_MANAGER.getSession(sessionId);
    }

    public ServiceContext clean() {
        CTX_LOCAL.remove();
        return this;
    }

    public ServiceRequest getServiceRequest() {
        return serviceRequest;
    }

    public void setServiceRequest(ServiceRequest serviceRequest) {
        this.serviceRequest = serviceRequest;
    }
}